package com.qqtech.admin.context;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.frame.model.Result;

public abstract class BaseFileController {
	public static final Logger log = LoggerFactory.getLogger(BaseFileController.class);

	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request;
	}

	public HttpServletResponse getResponse() {
		HttpServletResponse response = ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
		return response;
	}

	@ExceptionHandler
	public void exp(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		PrintWriter writer = null;
		try {
			String errStr = "图片上传异常";
			Result retDomain = new Result();
			retDomain.setCode(RespEnum.EXCEPTION.getCode());
			retDomain.setMsg(errStr);
			String json = JsonUtil.toJson(retDomain);
			writer = response.getWriter();
			writer.write(json);
			writer.flush();
			writer.close();
			log.error("文件上传系统异常,e={},{}", ex, ex.getStackTrace());
			ex.printStackTrace();
		} catch (Exception e) {
			log.error("文件上传系统异常,e={},{}", e, e.getStackTrace());
			e.printStackTrace();
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
}
